<template>
  <section class="component file-upload" :class="{ disable: disableUpload }">
    <el-button
      style="margin-right:10px"
      v-if="showSM === 1 || showSM === 2 || showSM === 3 || showSM === 4"
      @click="downloadMoClick()"
      >下载模板</el-button
    >

    <el-upload
      :headers="headers"
      ref="upload"
      class="upload"
      style="display:inline"
      multiple
      :before-upload="onBeforeUpload"
      :accept="accept"
      :on-exceed="handleExceed"
      :before-remove="onBeforeRemove"
      :file-list="fileList"
      :action="uploadUrl"
      :limit="fileNumberLimit ? fileNumberLimit : null"
      :show-file-list="showFileList"
      :on-success="onSucess"
      :on-progress="onProgress"
      :on-error="onError"
      :on-change="onChange"
      :on-remove="onRemove"
      :disabled="disabled"
      :list-type="listType"
      :on-preview="handlePictureCardPreview"
    >
      <el-button
        v-if="this.listType !== 'picture-card'"
        @click="clickHandle"
        :type="buttonType"
        :disabled="disabled"
        >{{ buttonName }}</el-button
      >
      <!-- 照片墙 -->
      <i class="el-icon-plus" v-show="this.listType === 'picture-card'"></i>
    </el-upload>
    <el-dialog
      :visible.sync="dialogVisible"
      width="400px"
      v-if="this.listType === 'picture-card'"
      :append-to-body="true"
    >
      <!-- <img width="360px" :src="dialogImageUrl" alt=""> -->
      <div class="demo-image__preview">
        <el-image
          :z-index="3000"
          :src="dialogImageUrl"
          :preview-src-list="urlFileList"
        >
        </el-image>
      </div>
    </el-dialog>

    <div
      style="font-size:12px;color:#1aaeec;border:1px solid #ccc;margin-top:20px"
      v-show="showSM === 1 || showSM === 2 || showSM === 3 || showSM === 4"
    >
      <div>说明：</div>
      <div>1:点击下载模板按钮，下载导入模板。</div>
      <div>2:按模板字段要求，填充数据并保存。</div>
      <div>3:点击上传文件按钮，上传数据到系统。</div>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Watch, Prop, Emit } from "vue-property-decorator";
import { State } from "vuex-class";
import { Dependencies } from "~/core/decorator";
import { NetService } from "~/utils/net.service";
import { commonService } from "~/config/server";
import app from "~/config/app.config";
import { Upload } from "element-ui";
import { StorageService } from "~/utils/storage.service";
import { FileUploadService } from "~/services/file-service/file-upload.service";
import { CaseOutContrastController } from "~/services/domain-service/case-out-contrast.service";
import { CaseOutRecordController } from "~/services/domain-service/case-out-record.service";

@Component({
  components: {}
})
export default class FileUpload extends Vue {
  @Dependencies(FileUploadService)
  private FileUpload: FileUploadService;
  @Dependencies(CaseOutContrastController)
  private caseOutContrastController: CaseOutContrastController;
  @Dependencies(CaseOutRecordController)
  private caseOutRecordController: CaseOutRecordController;

  @State
  private userToken;
  // 是否显示文件列表
  @Prop({ default: true })
  private showFileList;

  //按钮禁用
  @Prop()
  private disabled;
  // 允许的文件后缀类型
  @Prop({
    type: Array
  })
  private AllowExtension;
  @Prop({
    type: Number
  })
  private showSM;

  @Prop({ default: "text" }) private listType;

  @Prop({
    type: String
  })
  private recordFildId;

  @Prop({
    type: String
  })
  private accept;

  /**
   * 按钮文字
   */
  @Prop({ default: "上传文件" }) private buttonName;

  /**
   * 按钮的类型
   */
  @Prop({ default: "primary" }) private buttonType;

  // 文件数量限制
  @Prop({
    default: false,
    type: [Boolean, Number]
  })
  private fileNumberLimit;

  // 文件带下限制
  @Prop({
    default: 100,
    type: Number
  })
  private fileSizeLimit;

  // 文件列表
  @Prop({
    default: () => [],
    type: Array
  })
  private fileList;

  private dialogImageUrl: string = "";
  private dialogVisible: boolean = false;
  private urlFileList: any = [];

  // 上传成功回调事件
  @Emit("onUploadSuccess")
  private onUploadSucess(id, data) {
    this.updateFileList(data);
  }

  // 上传进度回调事件
  @Emit("onUploadProgress")
  private onUploadProgress(id, percent) {}

  // 上传异常回调事件
  @Emit("onUploadError")
  private onUploadError(id, error) {}

  // 更新文件列表
  @Emit("update:fileList")
  private updateFileList(fileList) {}

  //删除成功的回调事件
  @Emit("onUploadRemove")
  private onUploadRemove(file, fileList) {}

  // 上传文件回显
  @Watch("recordFildId")
  private recordFildIdChange(val) {
    const fileList: any = [];
    if (val) {
      val.split(",").map(val => {
        if (val) {
          this.FileUpload.getUploadFile(val).subscribe(data => {
            const temp: any = { ...data };
            temp.name = data.originalName;
            temp.response = {};
            temp.response.id = data.id;
            fileList.push(temp);
          });
        }
      });
    }
    this.updateFileList(fileList);
  }

  // 获取上传文件头部信息
  private get headers() {
    const token = StorageService.getItem("userToken") || "";
    return {
      "X-UserToken": token
    };
    // return {
    //   "X-UserToken": this.userToken
    // };
  }

  /**
   * 是否禁止上传
   */
  private get disableUpload() {
    return this.fileNumberLimit
      ? this.fileList.length >= this.fileNumberLimit
      : false;
  }

  /**
   * 上传路径
   */
  private get uploadUrl() {
    return [
      app.url.server,
      NetService.generateRequestUrl(commonService.uploadFileController.upload)
    ].join("/");
  }

  private clickHandle(event) {
    if (this.disableUpload) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  /**
   * 上传成功回调
   */
  private onSucess(data, { uid }) {
    this.onUploadSucess(uid, data);
  }

  /**
   * 上传进度回调
   */
  private onProgress({ percent }, { uid }) {}

  /**
   * 错误信息回调
   */
  private onError(err, file) {
    this.onUploadError(err, file);
  }

  /**
   * 文件上传状态改变回调
   */
  private onChange(file, uploadFileList) {
    switch (file.status) {
      case "ready": {
        this.fileList.push({
          uid: file.uid,
          name: file.name,
          percentage: file.percentage,
          status: file.status,
          url: file.url
        });
        break;
      }
    }
    this.updateFileList(this.fileList);
  }

  /**
   * 删除处理
   */
  private onRemove(file, fileList) {
    this.onUploadRemove(file, fileList);
    this.updateFileList(fileList);
    this.deleteInterface(file, fileList);
  }

  private deleteInterface(file, fileList) {
    if (!file.response && !file.response.id) return;
    this.FileUpload.deleteById(file.response.id).subscribe(data => {
      this.$message.success("删除成功！");
    });
  }

  /**
   * 删除预处理
   */
  private onBeforeRemove(file, fileList) {
    if (file.percentage === 0) {
      const list = fileList.filter(x => x.uid !== file.uid);
      this.updateFileList(list);
      return false;
    }
    return this.$confirm("是否确定删除该文件?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      this.$emit("close");
    });
  }

  /**
   * 上传文件预处理
   * 上传文件大小限制
   */
  private onBeforeUpload({ name, size, uid, type }) {

    console.log('name', name);
    
    if (this.AllowExtension && this.AllowExtension.length) {
      // 文件名异常
      if (name.toString().split(".").length < 2) {
        this.$message(`文件格式错误`);
        return false;
      }
      const [extension] = name.split(".").slice(-1);
      // console.log('[extension]', [extension]);
      // console.log(this.AllowExtension);
      // console.log('this.AllowExtension.includes(extension)', this.AllowExtension.includes(extension));
      
      if (!this.AllowExtension.includes(extension)) {
        this.$message(`文件格式不符合要求`);
        return false;
      }
    }
    // 限制上传文件大小
    if (this.fileSizeLimit * 1024 * 1024 < size) {
      this.$message(`文件${name}超过上传文件大小限制${this.fileSizeLimit}MB`);
      return false;
    }
  }

  private handleExceed(files, fileList) {
    if (this.fileNumberLimit) {
      this.$message.warning(
        `当前限制选择${this.fileNumberLimit}个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    }
  }

  private reset() {
    const upload = this.$refs["upload"] as any;
    upload.clearFiles();
    this.updateFileList([]);
  }
  /**
   * 下载模板
   */
  private downloadMoClick() {
    if (this.showSM === 1) {
      this.caseOutContrastController.downLoadBill().subscribe(data => {
        this.$common.downloadFile(data);
      });
    }
    if (this.showSM === 2) {
      this.caseOutContrastController
        .downLoadRepaymentRecord()
        .subscribe(data => {
          this.$common.downloadFile(data);
        });
    }
    if (this.showSM === 3) {
      this.caseOutRecordController.downLoadMobileUrge().subscribe(data => {
        this.$common.downloadFile(data);
      });
    }
    if (this.showSM === 4) {
      this.caseOutRecordController.downLoadOutVisit().subscribe(data => {
        this.$common.downloadFile(data);
      });
    }
  }

  /**
   * 照片墙图片显示
   */

  private handlePictureCardPreview(file) {
    this.dialogImageUrl = file.response.url;
    this.dialogVisible = true;
    this.urlFileList = this.fileList.map(v => v.response.url);
  }
}
</script>

<style lang="less">
.component.file-upload {
  .el-upload.el-upload--text {
    height: 25px !important;
    margin-top: -27px;
  }
}
</style>
